<template>
    <div class="orders-container">
        <h2>我的购买</h2>
        
        <div class="search-section">
            <el-form :inline="true" :model="orderListParm" class="search-form">
                <el-form-item label="订单号">
                    <el-input 
                        v-model="orderListParm.orderId" 
                        placeholder="请输入订单号"
                        clearable
                        @keyup.enter="handleSearch"
                    />
                </el-form-item>
                <el-form-item label="商品名称">
                    <el-input 
                        v-model="orderListParm.productName" 
                        placeholder="请输入商品名称"
                        clearable
                        @keyup.enter="handleSearch"
                    />
                </el-form-item>
                <el-form-item label="订单状态" >
                    <el-select 
                        v-model="orderListParm.status" 
                        placeholder="全部"
                        clearable
                        style="width: 100px;"
                        @change="handleSearch"
                    >
                        <el-option label="全部" :value="undefined" />
                        <el-option label="已创建" :value="1" />
                        <el-option label="支付中" :value="2" />
                        <el-option label="已支付" :value="3" />
                        <el-option label="已取消" :value="4" />
                        <el-option label="已超时" :value="5" />
                        <el-option label="支付失败" :value="6" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>

        <div v-loading="loading" class="orders-grid">
            <el-card v-for="order in orderList?.items" :key="order.orderId" class="order-card" shadow="hover">
                <div class="order-header">
                    <span class="order-id">订单号：{{ order.orderId }}</span>
                    <el-tag :type="getStatusType(order.orderStatus)" class="order-status">
                        {{ getStatusText(order.orderStatus) }}
                    </el-tag>
                </div>
                
                <div class="order-content">
                    <div class="order-info">
                        <h3 class="product-name">{{ order.orderTitle }}</h3>
                        <div class="price">${{ order.price }}</div>
                        <div class="time">{{ formatTime(order.createTime) }}</div>
                    </div>
                    
                    <div class="order-actions">
                        <el-button 
                            type="primary" 
                            link 
                            @click="showOrderDetail(order)"
                        >
                            查看详情
                        </el-button>
                        <el-button 
                            v-if="order.orderStatus === 1 || order.orderStatus === 6" 
                            type="success" 
                            link 
                            @click="createOrderStatement(order)"
                        >
                            立即支付
                        </el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <el-empty v-if="orderList?.items.length === 0" description="暂无订单" />

        <el-dialog
            v-model="dialogVisible"
            title="订单详情"
            width="50%"
            class="order-detail-dialog"
        >
            <div v-if="currentOrder" class="order-detail">
                <div class="detail-item">
                    <span class="label">订单号：</span>
                    <span>{{ currentOrder.orderId }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">商品名称：</span>
                    <span>{{ currentOrder.orderTitle }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">商品描述：</span>
                    <span>{{ currentOrder.orderDescribe }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">价格：</span>
                    <span class="price">${{ currentOrder.price }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">创建时间：</span>
                    <span>{{ formatTime(currentOrder.createTime) }}</span>
                </div>
                <div class="detail-item" v-if="currentOrder.updateTime">
                    <span class="label">更新时间：</span>
                    <span>{{ formatTime(currentOrder.updateTime) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">状态：</span>
                    <el-tag :type="getStatusType(currentOrder.orderStatus)">
                        {{ getStatusText(currentOrder.orderStatus) }}
                    </el-tag>
                </div>
                <div class="detail-item" v-if="currentOrder.failReason">
                    <span class="label">失败原因：</span>
                    <span class="fail-reason">{{ currentOrder.failReason }}</span>
                </div>
                <div class="detail-actions" v-if="currentOrder.orderStatus === 1">
                    <el-button type="success" @click="createOrderStatement(currentOrder)">立即支付</el-button>
                </div>
            </div>
        </el-dialog>

        <div class="pagination">
            <el-pagination layout="prev, pager, next" v-model:current-page="orderListParm.pageNo" :page-count="Number.parseInt(orderList?.page ?? '0')" @update:current-page="getOrderList()" />
        </div>
    </div>


    <el-dialog v-model="showLoginView" width="800" style="height: 500px;border-radius: 20px;background: linear-gradient(to bottom, #fbf0f2 10%, #ffffff);color: black;" center>
        <template #header>
            <h2 style="margin-top: 0px;">登录</h2>
        </template>
        <LoginView></LoginView> 
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import request from '@/base/request'
import { ElMessage } from 'element-plus'
import formatTime from '@/utils/formatTime'
import OrderListParm from '@/types/vip/OrderListParm'
import MyOrder from '@/types/vip/MyOrder'
import Page from '@/base/page'
import checkLogin from '@/utils/checkLogin'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const orderList = ref<Page<MyOrder>>()
const dialogVisible = ref(false)
const currentOrder = ref<MyOrder>(null)
const showLoginView = ref(false)

// 搜索表单
const orderListParm = ref<OrderListParm>({
    pageNo:1,
    pageSize:6
})

const getStatusType = (status: number) => {
    switch (status) {
        case 1: // CREATE
            return 'primary'
        case 2: // PAYING
            return 'warning'
        case 3: // PAYED
            return 'success'
        case 4: // CANCEL
            return 'info'
        case 5: // OVERTIME
            return 'danger'
        case 6: // FAIL
            return 'danger'
        default:
            return 'info'
    }
}

const getStatusText = (status: number) => {
    switch (status) {
        case 1: // CREATE
            return '已创建'
        case 2: // PAYING
            return '支付中'
        case 3: // PAYED
            return '已支付'
        case 4: // CANCEL
            return '已取消'
        case 5: // OVERTIME
            return '已超时'
        case 6: // FAIL
            return '支付失败'
        default:
            return '未知状态'
    }
}

const showOrderDetail = (order) => {
    currentOrder.value = order
    dialogVisible.value = true
}

const createOrderStatement = async (order) => {
    try {
        loading.value = true
        const response = await request.post(`/trade/orderStatement/createOrderStatement/${order.orderId}`)
        if (response.data.code === 200) {
            // 跳转到支付页面，使用路径参数
            window.open(`/home/payment/${response.data.data}`)
        } else {
            console.log(response.data.msg)
            ElMessage.error(response.data.msg || '拉取支付宝支付失败')
        }
    } catch (error) {
        console.log(error)
        ElMessage.error('拉取支付宝支付失败')
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    getOrderList()
}

const getOrderList = async () => {
    loading.value = true
    try {
        const response = await request.post('/trade/payOrderBase/getMyOrders',orderListParm.value)
        if (response.data.code === 200) {
            orderList.value = response.data.data
        } else {
            ElMessage.error(response.data.msg || '获取订单列表失败')
        }
    } catch (error) {
        ElMessage.error('获取订单列表失败')
    } finally {
        loading.value = false
    }
}

onMounted(async() => {
    const result=await checkLogin();
    if(result){
        getOrderList()
    }else{
        showLoginView.value=true
    }
})
</script>

<style scoped>
.orders-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
    color: #e5eaf3;
}

h2 {
    margin-bottom: 20px;
    color: #e5eaf3;
    font-size: 24px;
    font-weight: 600;
}

.search-section {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #1d1e1f;
    border-radius: 8px;
    border: 1px solid #363637;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.orders-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;
    padding: 10px;
}

.order-card {
    transition: all 0.3s ease;
    border-radius: 12px;
    overflow: hidden;
    background-color: #1d1e1f;
    border: 1px solid #363637;
}

.order-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #363637;
}

.pagination{
    text-align: center;
    margin-left: 70vh;
}

.order-id {
    color: #a8abb2;
    font-size: 14px;
}

.order-status {
    font-weight: 500;
}

.order-content {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.order-info {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.product-name {
    font-size: 18px;
    font-weight: 600;
    color: #e5eaf3;
    margin: 0;
}

.price {
    font-size: 20px;
    color: #f56c6c;
    font-weight: bold;
}

.time {
    color: #a8abb2;
    font-size: 14px;
}

.order-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    gap: 10px;
}

.order-detail-dialog {
    :deep(.el-dialog) {
        background-color: #1d1e1f;
        border: 1px solid #363637;
    }
    
    :deep(.el-dialog__title) {
        color: #e5eaf3;
    }
    
    :deep(.el-dialog__body) {
        padding: 30px;
        color: #e5eaf3;
    }
}

.order-detail {
    padding: 20px;
}

.detail-item {
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
}

.label {
    font-weight: bold;
    width: 100px;
    color: #a8abb2;
    flex-shrink: 0;
}

.fail-reason {
    color: #f56c6c;
}

.detail-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
}

@media (max-width: 768px) {
    .orders-grid {
        grid-template-columns: 1fr;
    }
    
    .search-form {
        flex-direction: column;
    }
    
    .el-form-item {
        margin-right: 0;
        width: 100%;
    }
}
</style> 